package cn.gemiman.daoyi.module.iot.service.jhlequipmentdevice;

import cn.gemiman.daoyi.framework.common.pojo.PageParam;
import cn.gemiman.daoyi.framework.common.pojo.PageResult;
import cn.gemiman.daoyi.framework.common.util.object.BeanUtils;
import cn.gemiman.daoyi.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.gemiman.daoyi.module.iot.controller.admin.jhlequipmentdevice.vo.JhlEquipmentDevicePageReqVO;
import cn.gemiman.daoyi.module.iot.controller.admin.jhlequipmentdevice.vo.JhlEquipmentDeviceSaveReqVO;
import cn.gemiman.daoyi.module.iot.dal.dataobject.jhlequipmentdevice.JhlEquipmentDeviceDO;
import cn.gemiman.daoyi.module.iot.dal.dataobject.jhlequipmentplace.JhlEquipmentPlaceDO;
import cn.gemiman.daoyi.module.iot.dal.mysql.jhlequipmentdevice.JhlEquipmentDeviceMapper;
import cn.gemiman.daoyi.module.iot.dal.mysql.jhlequipmentplace.JhlEquipmentPlaceMapper;
import cn.gemiman.daoyi.module.iot.open.jhl.InnoprojhlOpenApiService;
import cn.gemiman.daoyi.module.iot.open.jhl.vo.*;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.List;

import static cn.gemiman.daoyi.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.gemiman.daoyi.module.iot.enums.ErrorCodeConstants.JHL_EQUIPMENT_DEVICE_ADD_ERROR;
import static cn.gemiman.daoyi.module.iot.enums.ErrorCodeConstants.JHL_EQUIPMENT_DEVICE_NOT_EXISTS;

/**
 * 精华隆设备信息 Service 实现类
 *
 * @author 道一源码
 */
@Service
@Validated
public class JhlEquipmentDeviceServiceImpl implements JhlEquipmentDeviceService {

    @Resource
    private JhlEquipmentDeviceMapper jhlEquipmentDeviceMapper;
    @Resource
    private InnoprojhlOpenApiService innoprojhlOpenApiService;
    @Resource
    private JhlEquipmentPlaceMapper jhlEquipmentPlaceMapper;

    @Override
    public Integer asyncJhlEquipmentDevice(Integer... ids) {
        DeviceQueryReqVO reqVO = new DeviceQueryReqVO();
        reqVO.setPageNum(1);
        reqVO.setPageSize(10000);
        if (null != ids && ids.length > 0) {
            reqVO.setId(ids[0]);
        }
        int sum = 0;
        boolean hasNext;
        do {
            JSONObject resp = innoprojhlOpenApiService.queryDevice(reqVO);
            if (resp.getInt("code") == 200) {
                JSONObject data = resp.getJSONObject("data");
                hasNext = data.getInt("pages") > data.getInt("current");
                JSONArray records = data.getJSONArray("records");
                sum += records.size();
                records.forEach(record -> {
                    JSONObject place = (JSONObject) record;
                    JhlEquipmentDeviceDO bean = place.toBean(JhlEquipmentDeviceDO.class);
                    if (jhlEquipmentDeviceMapper.selectById(bean.getId()) == null) {
                        jhlEquipmentDeviceMapper.insert(bean);
                    } else {
                        jhlEquipmentDeviceMapper.updateById(bean);
                    }
                });
            } else {
                hasNext = false;
            }
        } while (hasNext);
        return sum;
    }

    @Override
    public Integer createJhlEquipmentDevice(JhlEquipmentDeviceSaveReqVO createReqVO) {
        String deviceIdentifier = createReqVO.getDeviceIdentifier();
        JhlEquipmentDeviceDO existsDO = jhlEquipmentDeviceMapper.selectOne(new LambdaQueryWrapperX<JhlEquipmentDeviceDO>()
                .eq(JhlEquipmentDeviceDO::getDeviceIdentifier, deviceIdentifier)
                .or().eq(JhlEquipmentDeviceDO::getMac, deviceIdentifier)
        );
        if (null != existsDO) {
            Integer id = existsDO.getId();
            this.asyncJhlEquipmentDevice(id);
            return id;
        }
        JSONObject existsDevice = innoprojhlOpenApiService.queryOneDevice(new DeviceQueryOneReqVO().setDeviceId(deviceIdentifier));
        if (existsDevice.getInt("code") == 200) {
            JSONObject data = existsDevice.getJSONObject("data");
            if (data != null && data.getInt("id") != null) {
                Integer id = data.getInt("id");
                this.asyncJhlEquipmentDevice(id);
                return id;
            }
        }
        // 校验是否为网关子设备
        JhlEquipmentDevicePageReqVO pageReqVO = new JhlEquipmentDevicePageReqVO();
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<JhlEquipmentDeviceDO> gatewayList = this.getJhlEquipmentDevicePage(pageReqVO.setDeviceTypes(CollUtil.toList("69001", "69002", "69003"))).getList();
        if (CollUtil.isNotEmpty(gatewayList)) {
            for (JhlEquipmentDeviceDO gatewayEd : gatewayList) {
                JSONObject querySubDevices = innoprojhlOpenApiService.querySubDevices(new QuerySubDevicesReqVO().setParentId(gatewayEd.getId()));
                if (querySubDevices.getInt("code") == 200) {
                    JSONArray data = querySubDevices.getJSONArray("data");
                    if (null != data && !data.isEmpty()) {
                        Object mac = data.stream().filter(o -> {
                            JSONObject subDevice = (JSONObject) o;
                            return StrUtil.equals(subDevice.getStr("mac"), deviceIdentifier);
                        }).findFirst().orElse(null);
                        if (null != mac) {
                            JSONObject macJson = (JSONObject) mac;
                            createReqVO.setDeviceType(macJson.getStr("deviceType"));
                            createReqVO.setParentId(gatewayEd.getId());
                            break;
                        }
                    }
                }
            }
        }
        if (null == createReqVO.getPlaceId()) {
            JhlEquipmentPlaceDO placeDO = jhlEquipmentPlaceMapper.selectOne(Wrappers.lambdaQuery(JhlEquipmentPlaceDO.class).orderByAsc(JhlEquipmentPlaceDO::getId), false);
            if (null != placeDO) {
                createReqVO.setPlaceId(placeDO.getId());
            } else {
                throw exception(JHL_EQUIPMENT_DEVICE_ADD_ERROR, 0, "没有可用的场所");
            }
        }
        JSONObject device = innoprojhlOpenApiService.createDevice(BeanUtil.toBean(createReqVO, DeviceCreateReqVO.class).setDeviceId(deviceIdentifier));
        if (device.getInt("code") != 200) {
            throw exception(JHL_EQUIPMENT_DEVICE_ADD_ERROR, device.getInt("code"), device.getStr("message"));
        }
        Integer id = device.getInt("data");
        existsDevice = innoprojhlOpenApiService.queryOneDevice(new DeviceQueryOneReqVO().setDeviceId(deviceIdentifier));
        if (existsDevice.getInt("code") == 200) {
            JSONObject data = existsDevice.getJSONObject("data");
            if (data != null && data.getInt("id") != null) {
                this.asyncJhlEquipmentDevice(id);
                return id;
            }
        }
        // 返回
        return id;
    }

    @Override
    public void updateJhlEquipmentDevice(JhlEquipmentDeviceSaveReqVO updateReqVO) {
        // 校验存在
        validateJhlEquipmentDeviceExists(updateReqVO.getId());
        // 更新
        JhlEquipmentDeviceDO updateObj = BeanUtils.toBean(updateReqVO, JhlEquipmentDeviceDO.class);
        jhlEquipmentDeviceMapper.updateById(updateObj);
    }

    @Override
    public void deleteJhlEquipmentDevice(Integer id) {
        // 校验存在
        validateJhlEquipmentDeviceExists(id);
        try {
            innoprojhlOpenApiService.deleteDevice(new DeviceDeleteReqVO().setId(id));
        } catch (Exception ignore) {
        }
        // 删除
        // jhlEquipmentDeviceMapper.deleteById(id);
        jhlEquipmentDeviceMapper.deleteAbsoluteById(id);
    }

    private void validateJhlEquipmentDeviceExists(Integer id) {
        if (jhlEquipmentDeviceMapper.selectById(id) == null) {
            throw exception(JHL_EQUIPMENT_DEVICE_NOT_EXISTS);
        }
    }

    @Override
    public JhlEquipmentDeviceDO getJhlEquipmentDevice(Integer id) {
        return jhlEquipmentDeviceMapper.selectById(id);
    }

    @Override
    public PageResult<JhlEquipmentDeviceDO> getJhlEquipmentDevicePage(JhlEquipmentDevicePageReqVO pageReqVO) {
        return jhlEquipmentDeviceMapper.selectPage(pageReqVO);
    }

    @Override
    public Integer asyncDeleteJhlEquipmentDevice() {
        List<JhlEquipmentDeviceDO> exists = jhlEquipmentDeviceMapper.selectList();
        int d = 0;
        if (CollUtil.isNotEmpty(exists)) {
            for (JhlEquipmentDeviceDO existsDO : exists) {
                JSONObject existsDevice = innoprojhlOpenApiService.queryOneDevice(new DeviceQueryOneReqVO().setId(existsDO.getId()));
                if (existsDevice.getInt("code") == 200) {
                    JSONObject data = existsDevice.getJSONObject("data");
                    if (data == null || data.getInt("id") == null) {
                        this.deleteJhlEquipmentDevice(existsDO.getId());
                        d++;
                    }
                }
            }
        }
        return d;
    }

}
